<template>
	<form-item-wrapper :designer="designer" :field="thisField" :rules="rules" :design-state="thisDesignState"
					   :parent-widget="thisParentWidget" :parent-list="thisParentList" :index-of-parent-list="thisIndexOfParentList" :style="field.options.customStyle"
					   :sub-form-row-index="thisSubFormRowIndex" :sub-form-col-index="thisSubFormColIndex" :sub-form-row-id="thisSubFormRowId">
		<el-image ref="imgRef" class="image" :src="fieldModel!=null?fieldModel.substring(0,(fieldModel.length)-32):null" :style="{height:thisField.options.columnHeight,width:thisField.options.columnWidth}"
				  fit="fill"></el-image>
		<div style="display: block;text-align: center;width: 100%" v-if="field.options.disabled==false">
			<el-button size="mini" @click="selectSign" v-if="field.options.signType.includes('1')">签章</el-button>
			<el-button @click="doSign" size="mini" v-if="field.options.signType.includes('2')">手写</el-button>
			<el-button @click="clearSign" size="mini" v-if="field.options.signType.length>0">清除</el-button>
		</div>
		<signDialog v-if="dialog.save" ref="signDialog" @success="handleSaveSuccess" @closed="dialog.save=false"></signDialog>
		<signSelectDialog v-if="dialog.selectSave" ref="signSelectDialog" @success="handleSaveSuccess" @closed="dialog.selectSave=false"></signSelectDialog>
	</form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import fieldMixin from "@/components/designer/form-designer/form-widget/field-widget/fieldMixin";
import signDialog from './signDialog'
import signSelectDialog from './signSelectDialog'

export default {
	name: "sign-widget",
	componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
	mixins: [emitter, fieldMixin],
	props: {
		field: Object,
		parentWidget: Object,
		parentList: Array,
		indexOfParentList: Number,
		designer: Object,
	},
	components: {
		FormItemWrapper,
		signDialog,
		signSelectDialog
	},

	data() {
		return {
			dialog: {
				save: false,
				selectSave:false
			},
			bindEls: [],
			thisField: this.field,
			thisParentWidget: this.parentWidget,
			thisParentList: this.parentList,
			thisIndexOfParentList: this.indexOfParentList,
			thisDesignState: this.designState,
			thisSubFormRowIndex: this.subFormRowIndex,
			thisSubFormColIndex: this.subFormColIndex,
			thisSubFormRowId: this.subFormRowId,
			oldFieldValue: null, //field组件change之前的值
			fieldModel: null,
			oldFieldModel: null,
			rules: [],
			bindField: this.field.options.bindField,
			md5Str: '',
			invalidBase64: "",

		}
	},
	computed: {
		inputType() {
			if (this.thisField.options.type === 'number') {
				return 'text'  //当input的type设置为number时，如果输入非数字字符，则v-model拿到的值为空字符串，无法实现输入校验！故屏蔽之！！
			}
			return this.thisField.options.type
		},
		getBindElsFieldModel() {
			let res = "";
				this.bindEls.forEach(item => {
					if(item!=undefined)
					{
						if(item.field.options.textContent)
						{
							res = res + item.field.options.textContent.split(":")[1];
						}else{
							res = res + item.fieldModel;
						}
					}
				})
			return res;
		}
	},
	watch: {
		"getBindElsFieldModel": {
			deep: true,
			immediate: true, // 是否初始化时就执行一次
			handler(val, old) {
				let nowMd5Str = this.$TOOL.crypto.MD5(val);
				if (nowMd5Str != this.md5Str) {
					this.fieldModel = this.invalidBase64 + this.md5Str;
				} else {
					this.fieldModel = this.oldFieldModel + this.md5Str;
				}
			}
		},
		"fieldModel": {
			handler(val) {
				this.handleChangeEvent(val);
			}
		},
	},
	beforeCreate() {
		/* 这里不能访问方法和属性！！ */
	},

	created() {
		/* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
		   需要在父组件created中初始化！！ */
		this.initFieldModel()
		this.registerToRefList()
		this.initEventHandler()
		this.buildFieldRules()
		this.handleOnCreated()
	},

	mounted() {
		this.handleOnMounted();
		this.initBindField();
	},

	beforeUnmount() {
		this.unregisterFromRefList()
	},

	methods: {
		initBindField() {
			if (this.fieldModel != null) {
				this.oldFieldModel = this.fieldModel.substring(0, (this.fieldModel.length) - 32);
				this.md5Str = this.fieldModel.substring((this.fieldModel.length) - 32, this.fieldModel.length);
			}
			if (this.field.options.bindField != '') {
				let bFieldArr = this.bindField.split(",");
				bFieldArr.forEach(item => {
					this.bindEls.push(this.refList[item]);
				})
			}
		},
		getBindFieldSignFlag() {
			let v = "";
			if (this.bindField != '') {
				let arr = this.bindField.split(",");
				arr.forEach(item => {
					v = v + this.refList[item].fieldModel;
				})
			}
			this.md5Str = this.$TOOL.crypto.MD5(v);
		},
		clearSign() {
			this.fieldModel = null;
		},
		selectSign()
		{
			this.$prompt('请输入印章密码!', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputType:'password',
			}).then(({ value }) => {
				this.dialog.selectSave = true
				this.$nextTick(() => {
					this.$refs.signSelectDialog.open().setData(value)
				})
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '取消输入'
				});
			});
		},
		doSign() {
			this.dialog.save = true
			const w = this.$refs.imgRef.$el.offsetWidth
			const h = this.$refs.imgRef.$el.offsetHeight
			let sizeData = {
				width: w,
				height: h
			}
			this.$nextTick(() => {
				this.$refs.signDialog.open().setData(sizeData)
			})
		},
		handleSaveSuccess(resultImg) {
			this.getBindFieldSignFlag();
			this.fieldModel = resultImg + this.md5Str;
		}
	}
}
</script>

<style lang="scss" scoped>
@import "../../../../../assets/formdesigner/styles/global.scss"; /* form-item-wrapper已引入，还需要重复引入吗？ */

</style>
